package com.ruizhong.centercontroll;

import com.ruizhong.centercontroll.controller.OtherSystemController;
import com.ruizhong.centercontroll.service.TLanguageService;
import com.ruizhong.centercontroll.util.Server;
//import javafx.application.Application;
//import javafx.stage.Stage;
import me.friwi.jcefmaven.*;
import me.friwi.jcefmaven.impl.progress.ConsoleProgressHandler;
import org.cef.CefApp;
import org.cef.CefClient;
import org.cef.browser.CefBrowser;
import org.cef.browser.CefFrame;
import org.cef.browser.CefMessageRouter;
import org.cef.callback.CefQueryCallback;
import org.cef.handler.CefMessageRouterHandlerAdapter;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Map;

@SpringBootApplication
@EnableScheduling
public class WebApplication {


    private static TLanguageService tLanguageService;

    private static ConfigurableApplicationContext context;


    public static void main(String[] args) throws Exception {
        SpringApplicationBuilder springBuilder = new SpringApplicationBuilder(WebApplication.class);
        context = springBuilder.headless(false).run(args);
        System.setProperty("java.awt.headless", "false");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Server.start();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (AWTException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        String osName = System.getProperty("os.name").toLowerCase();
        System.out.println("当前osname的值为："+osName);
        if (!osName.contains("win")){

        }else {

            String localIp = OtherSystemController.getLocalIp();

            Thread windowThread = new Thread(new Runnable() {
                @Override
                public void run() {

                    try {
                        CefAppBuilder builder = new CefAppBuilder();
                        boolean useOSR = false;
                        builder.getCefSettings().windowless_rendering_enabled = useOSR;
                        builder.setAppHandler(new MavenCefAppHandlerAdapter() {
                            @Override
                            public void stateHasChanged(CefApp.CefAppState state) {
                                // 关闭应用时退出jvm运行
                                if (state == CefApp.CefAppState.TERMINATED) System.exit(0);
                            }
                        });

                        // 设置cef运行参数，这里为空
                        builder.addJcefArgs(args);
                        builder.setProgressHandler(new ConsoleProgressHandler());
                        // 设置 cef chrome实例的目录，关键，若不设置他会默认从网络中下载，国外网络可能下载不稳定导致失败
                        // 我的 cef chrome 位于项目的chrome目录下 C:\Users\Administrator\Desktop\project\java\demo-desktop\chrome
                        builder.setInstallDir(new File("jcef-bundle"));


                        // 全局的 CefApp 每个程序只能有一个，线程安全
                        CefApp build = builder.build();
                        // 显示一些版本信息
                        CefBuildInfo buildInfo = CefBuildInfo.fromClasspath();
                        System.out.println(buildInfo);
                        CefApp.CefVersion cefVersion = build.getVersion();
                        System.out.println(cefVersion);

                        // 创建一个浏览器客户端实例
                        CefClient client = build.createClient();
                        // 添加一个方法用于html调用它，在html中执行 window.javaQuery({...})
                        CefMessageRouter.CefMessageRouterConfig config = new CefMessageRouter.CefMessageRouterConfig();
                        config.jsQueryFunction = "javaQuery";// 定义方法
                        config.jsCancelFunction = "javaQueryCancel";// 定义取消方法
                        CefMessageRouter messageRouter = CefMessageRouter.create(config);
                        messageRouter.addHandler(new CefMessageRouterHandlerAdapter() {
                            @Override
                            public boolean onQuery(CefBrowser browser, CefFrame frame, long queryId, String request, boolean persistent, CefQueryCallback callback) {
                                if ("my_call".equals(request)) {
                                    // 返回影响成功的数据
                                    callback.success("get java data success!");
                                    browser.executeJavaScript("htmlFun('哈哈')", null, 2);// 调用js中定义的方法
                                    // callback.failure();
                                    return true;
                                }
                                return false;
                            }
                        }, false);
                        client.addMessageRouter(messageRouter);

                        boolean isTransparent = true;// 透明背景

                        // 创建一个浏览器实例，设置访问 url https://www.baidu.com
                        CefBrowser browser = client.createBrowser("http://" + localIp + ":8094", useOSR, isTransparent);
                        // 获取UI组件
                        Component uiComponent = browser.getUIComponent();


                        JButton backButton = new JButton("<");
                        JButton forwardButton = new JButton(">");
                        JButton refreshButton = new JButton("↻");


                        // 创建 JFrame UI 用于放入chrome
                        JFrame main = new JFrame("中控系统");
                        main.getContentPane().add(uiComponent, BorderLayout.CENTER);
                        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                        JPanel buttonPanel = new JPanel();
                        buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
                        buttonPanel.add(Box.createHorizontalStrut(10));
                        buttonPanel.add(refreshButton);
                        buttonPanel.add(backButton);
                        buttonPanel.add(forwardButton);
                        buttonPanel.add(Box.createHorizontalStrut(10));

                        backButton.addActionListener(new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent e) {
                                browser.goBack();
                            }
                        });

                        forwardButton.addActionListener(new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent e) {
                                browser.goForward();
                            }
                        });

                        refreshButton.addActionListener(new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent e) {
                                browser.reload();
                            }
                        });
                        main.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
                        // 获取屏幕的宽度和高度
                        int screenWidth = (int) screenSize.getWidth();
                        int screenHeight = (int) screenSize.getHeight();
                        // 设置舞台（窗口）
                        int windowWidth = screenWidth * 3 / 4;
                        int windowHeight = screenHeight * 3 / 4;
                        main.setSize(windowWidth, windowHeight);//大小
                        main.setLocation(0, 0);//位置

                        main.setVisible(true);//显示
                        main.addWindowListener(new WindowAdapter() {
                            @Override
                            public void windowClosing(WindowEvent e) {
                                // 关闭应用时要释放资源
                                CefApp.getInstance().dispose();
                                main.dispose();
                                System.exit(0);//0正常退出，1非正常退出
                            }
                        });
                        tLanguageService = context.getBean(TLanguageService.class);
                        Map<String, Object> settings = tLanguageService.getSettings();
                        Object minimizeOnStartup = settings.get("MinimizeOnStartup");
                        if (minimizeOnStartup != null && (Boolean) minimizeOnStartup) {
                            main.setState(Frame.ICONIFIED);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (UnsupportedPlatformException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (CefInitializationException e) {
                        e.printStackTrace();
                    }
                }
            });
            windowThread.start();
        }
    }

    public static InetAddress getLocalHostLANAddress() throws UnknownHostException {
        try {
            InetAddress candidateAddress = null;
            // 遍历所有的网络接口
            for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
                NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
                // 在所有的接口下再遍历IP
                for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) {
                    InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                    if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
                        if (inetAddr.isSiteLocalAddress()) {
                            // 如果是site-local地址，就是它了
                            return inetAddr;
                        } else if (candidateAddress == null) {
                            // site-local类型的地址未被发现，先记录候选地址
                            candidateAddress = inetAddr;
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                return candidateAddress;
            }
            // 如果没有发现 non-loopback地址.只能用最次选的方案
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            if (jdkSuppliedAddress == null) {
                throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
            }
            return jdkSuppliedAddress;
        } catch (Exception e) {
            UnknownHostException unknownHostException = new UnknownHostException(
                    "Failed to determine LAN address: " + e);
            unknownHostException.initCause(e);
            throw unknownHostException;
        }
    }

    public static void launch() throws Exception {
//        String url = "http://127.0.0.1:8094";
//        BrowserContext browserContext = BrowserContext.defaultContext();
//        Browser browser = new Browser(browserContext);
//        browser.getCacheStorage().clearCache();
//        BrowserView view = new BrowserView(browser);
//// 创建按钮
//        JButton backButton = new JButton("<");
//        JButton forwardButton = new JButton(">");
//        JButton refreshButton = new JButton("↻");
//        browser.loadURL(url);
//
//        // 设置按钮动作
//        backButton.addActionListener(new ActionListener() {
//            @Override
//            public void actionPerformed(java.awt.event.ActionEvent e) {
//                browser.goBack();
//            }
//        });
//        forwardButton.addActionListener(new ActionListener() {
//            @Override
//            public void actionPerformed(java.awt.event.ActionEvent e) {
//                browser.goForward();
//            }
//        });
//        refreshButton.addActionListener(new ActionListener() {
//            @Override
//            public void actionPerformed(ActionEvent e) {
//                browser.reload();
//            }
//        });
//
//        // 创建面板并添加组件
//        JPanel panel = new JPanel();
//        panel.setLayout(new BorderLayout());
//        panel.add(view, BorderLayout.CENTER);
//
//        JPanel buttonPanel = new JPanel();
//        buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
//        buttonPanel.add(Box.createHorizontalStrut(10));
//        buttonPanel.add(refreshButton);
//        buttonPanel.add(backButton);
//        buttonPanel.add(forwardButton);
//        buttonPanel.add(Box.createHorizontalStrut(10));
//
//        panel.add(buttonPanel, BorderLayout.SOUTH);
//
//        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//
//        // 获取屏幕的宽度和高度
//        int screenWidth = (int) screenSize.getWidth();
//        int screenHeight = (int) screenSize.getHeight();
//
//        // 创建窗口
//        JFrame frame = new JFrame("AWT Browser Example");
//        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//        frame.setSize(screenWidth, screenHeight);
//        frame.add(panel);
//        frame.setVisible(true);


    }

//    @Override
//    public void start(Stage primaryStage) throws Exception {
//        String url = "http://127.0.0.1:8080";
//        BrowserContext browserContext = BrowserContext.defaultContext();
//        Browser browser = new Browser(browserContext);
//        browser.getCacheStorage().clearCache();
//
//        com.teamdev.jxbrowser.chromium.javafx.BrowserView view = new com.teamdev.jxbrowser.chromium.javafx.BrowserView(browser);
//
//
//        javafx.scene.control.Button backButton = new javafx.scene.control.Button("<");
//
//        backButton.setOnAction(new EventHandler<javafx.event.ActionEvent>() {
//            @Override
//            public void handle(javafx.event.ActionEvent event) {
//                browser.goBack();
//            }
//        });
//
//        javafx.scene.control.Button forwardButton = new Button(">");
//        forwardButton.setOnAction(new EventHandler<javafx.event.ActionEvent>() {
//            @Override
//            public void handle(javafx.event.ActionEvent event) {
//                browser.goForward();
//            }
//        });
//
//        javafx.scene.control.Button refreshButton = new Button("↻");
//        refreshButton.setOnAction(new EventHandler<javafx.event.ActionEvent>() {
//            @Override
//            public void handle(javafx.event.ActionEvent event) {
//                browser.reload();
//            }
//        });
//
//        HBox buttonBox = new HBox(10, backButton, forwardButton, refreshButton);
//        buttonBox.setAlignment(Pos.CENTER_RIGHT);
//        buttonBox.setPadding(new Insets(10));
//
//        BorderPane root = new BorderPane();
//        root.setCenter(view);
//        root.setBottom(buttonBox);
//
//        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//
//        // 获取屏幕的宽度和高度
//        int screenWidth = (int) screenSize.getWidth();
//        int screenHeight = (int) screenSize.getHeight();
//        // 设置舞台（窗口）
//        primaryStage.setTitle("中控系统");
//        int windowWidth = screenWidth/2;
//        int windowHeight = screenHeight/2;
//        // 创建一个场景并将布局容器添加到其中
//        Scene scene = new Scene(root,windowWidth,windowHeight);
//
//        // 设置舞台的场景
//        primaryStage.setScene(scene);
//
//        // 加载网页
//        browser.loadURL(url);
//
//
//        // 显示舞台
//        primaryStage.show();
//
//        // 添加窗口关闭事件监听器（可选）
//        primaryStage.setOnCloseRequest(event -> {
//            System.out.println("窗口关闭...");
//            if (context != null) {
//                context.close();
//            }
//
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    browser.dispose();
//                    System.exit(0);
//                }
//            }).start();
//            // 这里可以添加其他关闭前的处理逻辑，比如释放资源等
//        });
//    }
}
